package com.neusoft.databus.policy.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.neusoft.bizcore.common.utils.CacheUtil;
import com.neusoft.databus.policy.bean.ComplexPolicyExtendBean;
import com.neusoft.databus.policy.enums.PolicyType;
import com.neusoft.databus.policy.model.Policy;

/**
 * 策略相关工具类
 *
 * @author hanbq
 * @date 2015-3-10 下午4:45:33
 */
public class PolicyUtil {
    public static final String APPLICATIONNAME = "POLICY";
    public static final String LINKAGE_SYMBOL = "@";
    public static final String FREQUENCY = "FREQUENCY";
    public static final String COMPLEXPOLICY = "COMPLEXPOLICY";
    public static final String HISTORY = "HISTORY";
    public static final String OLDMETRICVALUE = "OLDMETRICVALUE";
    public static final String EVENT = "EVENT";
    public static final String SUSPENDTIME = "SUSPEND_TIME";
    public static final String SUSPENDCOUNT = "SUSPEND_COUNT";
    public static final String COUNT = "COUNT";

    /**
     * 字符串MD5转换
     *
     * @param sourceStr
     * @return
     * @author hanbq
     * @throws NoSuchAlgorithmException
     * @date 2015-3-24 下午2:06:22
     */
    public static String toMD5(final String sourceStr) throws NoSuchAlgorithmException {
        final MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(sourceStr.getBytes());
        final byte b[] = md.digest();
        int i;
        final StringBuffer buf = new StringBuffer("");
        for (final byte element : b) {
            i = element;
            if (i < 0) {
                i += 256;
            }
            if (i < 16) {
                buf.append("0");
            }
            buf.append(Integer.toHexString(i));
        }
        return buf.toString();
    }

    public static boolean isNumber(final String str) {
        final Pattern pattern = Pattern.compile("^[+-]?\\d+(\\.\\d+)?$");
        final Matcher matcher = pattern.matcher(str);
        return matcher.find();
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String getEventCode(final String resourceCode, final String policyCode) {
        final StringBuffer code = new StringBuffer(resourceCode);
        code.append(PolicyUtil.LINKAGE_SYMBOL).append(policyCode);
        return code.toString();
    }

    public static String getErrorMsg(final Exception e) {
        StringWriter errors = null;
        PrintWriter print = null;
        try {
            errors = new StringWriter();
            print = new PrintWriter(errors);
            e.printStackTrace();
            if (print != null) {
                print.close();
            }
            return errors.toString();
        } finally {
            try {
                if (errors != null) {
                    errors.close();
                }
            } catch (final IOException e1) {
                e1.getStackTrace();
            }
        }
    }

    public static Map<String, Object> convertToObjectMap(final Map<String, String> source) {
        Map<String, Object> rets = null;
        if ((source != null) && (source.size() > 0)) {
            rets = new HashMap<>();
            for (final Entry<String, String> entry : source.entrySet()) {
                rets.put(entry.getKey(), entry.getValue());
            }
        }
        return rets;
    }

    public static String getFrequencyKey(final String resourceCode, final Policy policy) {
        final StringBuffer key = new StringBuffer();
        final String[] args = {PolicyUtil.FREQUENCY, resourceCode, String.valueOf(policy.getId()) };
        key.append(CacheUtil.keyBuilder(PolicyUtil.APPLICATIONNAME, args));
        return key.toString();
    }

    public static String getComplexPolicyKey(final String resourceCode, final Policy policy) {
        final StringBuffer key = new StringBuffer();
        final String[] args =
                {PolicyUtil.COMPLEXPOLICY, resourceCode, String.valueOf(policy.getId()), policy.getCode() };
        key.append(CacheUtil.keyBuilder(PolicyUtil.APPLICATIONNAME, args));
        return key.toString();
    }

    public static String getOldMetricValueKey(final String resourceCode, final Long policyId,
            final String metricCode) {
        final StringBuffer key = new StringBuffer();
        final String[] args =
                {PolicyUtil.OLDMETRICVALUE, resourceCode, String.valueOf(policyId), metricCode };
        key.append(CacheUtil.keyBuilder(PolicyUtil.APPLICATIONNAME, args));
        return key.toString();
    }

    public static String getHistoryKey(final ComplexPolicyExtendBean extendBean) {
        final StringBuffer key = new StringBuffer();
        final String[] args = {PolicyUtil.HISTORY, extendBean.getMetricCode(), extendBean.getExpressKey() };
        key.append(CacheUtil.keyBuilder(PolicyUtil.APPLICATIONNAME, args));
        return key.toString();
    }

    public static String getEventKey(final String resourceCode, final String policyCode) {
        final StringBuffer key = new StringBuffer();
        final String[] args = {PolicyUtil.EVENT, resourceCode, policyCode };
        key.append(CacheUtil.keyBuilder(PolicyUtil.APPLICATIONNAME, args));
        return key.toString();
    }

    public static String getSuspendTimeKey(final String resourceCode, final Policy policy) {
        final StringBuffer key = new StringBuffer();
        final String[] args = {PolicyUtil.SUSPENDTIME, resourceCode, String.valueOf(policy.getId()) };
        key.append(CacheUtil.keyBuilder(PolicyUtil.APPLICATIONNAME, args));
        return key.toString();
    }

    public static String getSuspendCountKey(final String resourceCode, final Policy policy) {
        final StringBuffer key = new StringBuffer();
        final String[] args = {PolicyUtil.SUSPENDCOUNT, resourceCode, String.valueOf(policy.getId()) };
        key.append(CacheUtil.keyBuilder(PolicyUtil.APPLICATIONNAME, args));
        return key.toString();
    }

    public static String getEventCountKey(final PolicyType policyType) {
        final StringBuffer key = new StringBuffer();
        final String[] args = {PolicyUtil.COUNT, policyType.toString() };
        key.append(CacheUtil.keyBuilder(PolicyUtil.APPLICATIONNAME, args));
        return key.toString();
    }
}
